<template>
  <div class="components-container">
    <split-pane :default-percent="30" split="vertical">
      <template slot="paneL">
        <!--菜单树-->
        <div class="menu-tree-container bg">
          <el-input v-model="filterText" clearable placeholder="输入关键字进行过滤" style="margin-bottom:30px;"/>
          <div style="height:calc(100vh - 230px);overflow-y: scroll;">
            <el-tree
              v-loading="menuLoading"
              ref="tree"
              :data="internationalMenuTree"
              :props="defaultProps"
              :filter-node-method="filterNode"
              :highlight-current="true"
              :expand-on-click-node="false"
              :check-on-click-node="true"
              node-key="id"
              default-expand-all
              class="filter-tree"
              @node-click="onclickTree"/>
          </div>
        </div>
      </template>
      <template slot="paneR">
        <div>
          <!--增加菜单弹窗-->
          <el-dialog :visible.sync="dialogAddVisible" title="增加菜单">
            <el-form ref="addFrom" :model="addMenuData" :rules="addRules">
              <el-form-item :label-width="formLabelWidth" label="上级菜单：">
                <el-cascader
                  ref="cascader"
                  :options="internationalMenuTree"
                  :props="defaultProps"
                  :show-all-levels="false"
                  v-model="addMenuData.pidPaths"
                  change-on-select
                  clearable
                  expand-trigger="hover"/>
                <br>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" label="菜单名称：" prop="name">
                <el-input v-model="addMenuData.name" clearable/>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" label="路径：" prop="url">
                <el-input v-model="addMenuData.url" clearable/>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" label="图标：" prop="icon">
                <el-input v-model="addMenuData.icon" clearable/>
              </el-form-item>
              <el-form-item :label-width="formLabelWidth" label="排序：" prop="orderNum">
                <el-input v-model.number="addMenuData.orderNum" clearable/>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogAddVisible = false">取 消</el-button>
              <el-button type="primary" @click.stop="addMenu()">确 定</el-button>
            </div>
          </el-dialog>

          <div class="menu-title">
            <span>菜单详情</span>
            <span>
              <!-- 增加按钮 -->
              <el-button type="primary" size="mini" class="right" @click="openAddFunC">新增</el-button>
            </span>
          </div>
          <!--菜单详情-->
          <div class="menu-container bg">
            <div class="right">
              <!-- 修改 -->
              <el-button type="info" size="mini" @click="toEditor">修改</el-button>
              <!-- 删除 -->
              <el-button type="danger" size="mini" @click.native.prevent="deleteRow(checkMenu.id)">删除</el-button>
            </div>
            <div class="menu">
              <el-row :gutter="30" class="menu-item">
                <el-col :span="8"><span class="row-right-container">菜单名称 :</span></el-col>
                <el-col :span="14"><span>{{ checkMenu.title }}</span></el-col>
              </el-row>
              <el-row :gutter="30" class="menu-item">
                <el-col :span="8"><span class="row-right-container">路径 :</span></el-col>
                <el-col :span="14"><span class="left-menu-name">{{ checkMenu.url }}</span></el-col>
              </el-row>
              <el-row :gutter="30" class="menu-item">
                <el-col :span="8"><span class="row-right-container">图标 :</span></el-col>
                <el-col :span="14"><span class="left-menu-name">{{ checkMenu.icon }}</span></el-col>
              </el-row>
              <el-row :gutter="30" class="menu-item">
                <el-col :span="8"><span class="row-right-container">排序 :</span></el-col>
                <el-col :span="14"><span class="left-menu-name">{{ checkMenu.orderNum }}</span></el-col>
              </el-row>
            </div>
          </div>
          <div style="margin-top: 50px;">
            <el-divider/>
            <span class="menu-title">按钮</span>
          </div>
          <div class="right-container-bottom bg">
            <!-- 按钮管理 -->
            <!--<el-button type="primary" size="small" class="btn-manager" @click="btnManagerment(checkMenu.id)">按钮管理</el-button>-->
            <!--<el-dialog :title="'【'+ checkMenu.name +'】按钮'" :visible.sync="dialogBtnVisible">-->
            <el-table :data="btnData" fit highlight-current-row>
              <el-table-column align="center" label="名称">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input v-model="scope.row.name" :placeholder="scope.row.name" clearable size="small"/>
                  </template>
                  <span v-else>{{ scope.row.title }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="权限标识">
                <template slot-scope="scope">
                  <template v-if="scope.row.edit">
                    <el-input
                      v-model="scope.row.code"
                      :placeholder="scope.row.code"
                      clearable
                      size="small"/>
                  </template>
                  <span v-else>{{ scope.row.code }}</span>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作" min-width="200">
                <template slot-scope="scope">
                  <div v-if="scope.row.edit">
                    <!--取消编辑-->
                    <el-button
                      v-if="scope.row.edit"
                      type="warning"
                      size="mini"
                      icon="el-icon-back"
                      circle
                      @click="cancelEdit(scope.row)"/>
                    <!--提交-->
                    <el-button
                      type="success"
                      size="mini"
                      icon="el-icon-check"
                      circle
                      @click="confirmEdit(scope.row)"/>
                  </div>
                  <div v-else>
                    <!--编辑-->
                    <el-button
                      type="primary"
                      size="mini"
                      icon="el-icon-edit"
                      circle
                      @click="scope.row.edit=!scope.row.edit"/>
                    <!--删除-->
                    <el-button
                      type="danger"
                      size="mini"
                      icon="el-icon-delete"
                      circle
                      @click.native.prevent="BtndeleteRow(scope.$index, btnData)"/>
                  </div>
                </template>
              </el-table-column>
            </el-table>
            <div class="add-table-btn">
              <i class="el-icon-circle-plus-outline" @click="addTableColumn"/>
            </div>
            <!--<div slot="footer" class="dialog-footer">-->
            <!--<el-button @click="dialogBtnVisible = false">取 消</el-button>-->
            <!--</div>-->
            <!--</el-dialog>-->

            <!--编辑弹窗-->
            <el-dialog :title="'编辑【'+ checkMenu.title +'】菜单'" :visible.sync="dialogEditorVisible">
              <el-form ref="editor" :model="menu" :rules="addRules">
                <el-form-item :label-width="formLabelWidth" label="父节点：">
                  <el-cascader
                    ref="cascader"
                    :options="internationalMenuTree"
                    :props="defaultProps"
                    :show-all-levels="false"
                    v-model="menu.pidPaths"
                    change-on-select
                    expand-trigger="hover"
                    clearable/>
                  {{ menu.pidPaths }}
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="菜单名称：" prop="name">
                  <el-input v-model="menu.name" clearable/>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="路径：" prop="url">
                  <el-input v-model="menu.url" clearable/>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="图标：" prop="icon">
                  <el-input v-model="menu.icon" clearable/>
                </el-form-item>
                <el-form-item :label-width="formLabelWidth" label="排序：" prop="orderNum">
                  <el-input v-model.number="menu.orderNum" clearable/>
                </el-form-item>
              </el-form>
              <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditorVisible = false">取 消</el-button>
                <el-button type="primary" @click.stop="SureToEditor()">确 定</el-button>
              </div>
            </el-dialog>
          </div>
        </div>
      </template>
    </split-pane>
  </div>
</template>

<script>
import {
  getMenuTree,
  MenuAddFunC,
  MenuChangeFunC,
  getButtonByIdFunC,
  buttonChangeBtnFunC,
  buttonAddBtnFunC,
  buttonDelBtnFunC,
  MenuDelFunC
} from '@/api/menu';
import splitPane from 'vue-splitpane';
import {
  Message,
  MessageBox
} from 'element-ui';
import { translateMenuTree } from '@/utils/index';

export default {
  name: 'Menu',
  components: {
    splitPane
  },
  data() {
    return {
      dialogAddVisible: false, // 增加弹窗默认不显示
      dialogBtnVisible: false, // 按钮管理弹窗默认不显示
      dialogEditorVisible: false, // 修改弹窗默认不显示
      addMenuData: { //  增加弹窗中数据
        id: null,
        pid: null,
        pidPath: null,
        pidPaths: [],
        icon: null,
        url: null,
        name: null,
        orderNum: null
      },
      menu: { //  修改弹窗中数据
        id: null,
        pid: null,
        pidPath: null,
        pidPaths: null,
        icon: null,
        url: null,
        name: null,
        orderNum: null
      },
      addRules: { // 验证规则
        icon: [{
          required: true,
          trigger: 'blur'
        }],
        url: [{
          required: true,
          trigger: 'blur'
        }],
        name: [{
          required: true,
          trigger: 'blur'
        }],
        orderNum: [{
          required: true,
          trigger: 'blur'
        }, {
          type: 'number',
          message: '排序必须为数字值',
          trigger: ['blur', 'change']
        }]
      },
      btnData: [], // 按钮管理弹窗中的数据
      formLabelWidth: '100px',
      filterText: '',
      menus: [], // 树结构返回结果
      defaultProps: { // 下拉选择父节点配置
        children: 'children',
        label: 'title',
        value: 'id'
      },
      menuLoading: true,
      checkMenu: {} // 被点击节点数据
    };
  },
  computed: {
    internationalMenuTree() {
      return translateMenuTree(this.menus, this.$t.bind(this));
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.init();
  },
  methods: {
    // 初始化 树结构获取菜单
    init() {
      this.menuLoading = false;
      getMenuTree().then(response => {
        this.menus = response.data;
        this.menuLoading = false;
        this.checkMenu = translateMenuTree(response.data[0].data, this.$t.bind(this)); //  默认选中第一个节点
        this.btnManagerment();
        this.$nextTick(function() {
          this.$refs.tree.setCurrentKey(this.checkMenu.id);
        });
      });
    },

    // 对树节点进行筛选
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },

    // 树节点被点击时的回调
    onclickTree(menu) {
      console.log('点击节点', menu);
      this.checkMenu = menu.data; // 获取节点详情
      this.btnManagerment();
    },

    /** *************增加 *************/
    // 点击新增 出现弹窗
    openAddFunC() {
      const addJson = JSON.parse(JSON.stringify(this.checkMenu));
      if (addJson.pidPath && addJson.pidPaths) {
        addJson.pidPaths.push(addJson.id.toString());
        addJson.pidPath = addJson.pidPaths.join(',');
      } else {
        addJson.pidPaths = [];
        addJson.pidPaths.push(addJson.id.toString());
        addJson.pidPath = addJson.pidPaths.join(',');
      }
      this.addMenuData.pid = addJson.pid ? addJson.pid : null;
      this.addMenuData.pidPaths = addJson.pidPaths ? addJson.pidPaths : [];
      this.addMenuData.pidPath = addJson.pidPath ? addJson.pidPath : null;
      this.dialogAddVisible = true;
      this.$nextTick(function() {
        this.$refs.addFrom.resetFields(); // 移除校验结果
      });
      // 清空父节点
      const obj = {};
      obj.stopPropagation = () => {
      };
      // this.$refs.cascader.clearValue(obj)
    },
    // 新增按钮弹窗界面 点击确定按钮
    addMenu() {
      if (this.addMenuData.icon === null || this.addMenuData.name === null || this.addMenuData.orderNum === null || this.addMenuData.url === null) {
        Message({
          message: '请认真填写每一项',
          type: 'error',
          duration: 5 * 1000
        });
      } else {
        this.addMenuData.pid = this.addMenuData.pidPaths != null && this.addMenuData.pidPaths.length != 0 ? this.addMenuData.pidPaths[this.addMenuData.pidPaths.length - 1] : null;
        this.addMenuData.pidPath = this.addMenuData.pidPaths != null && this.addMenuData.pidPaths.length != 0 ? this.addMenuData.pidPaths.join(',') : null;
        console.log(this.addMenuData);
        MenuAddFunC(
          this.addMenuData.icon,
          this.addMenuData.name,
          this.addMenuData.orderNum,
          this.addMenuData.pidPath,
          this.addMenuData.pid,
          this.addMenuData.url
        ).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: '增加成功',
              type: 'success'
            });
            this.dialogAddVisible = false;
            this.init();
          } else {
            this.$message({
              message: '增加失败',
              type: 'error'
            });
          }
        });
      }
    },

    /** *************按钮管理 *************/
    // 点击按钮管理 弹出弹窗
    btnManagerment() {
      const menuId = this.checkMenu.id;
      if (menuId == '') {
        this.$message({
          message: '请先选择要管理的菜单',
          type: 'error'
        });
        return;
      }
      this.dialogBtnVisible = true;
      getButtonByIdFunC(menuId).then((res) => {
        if (res.data == []) {
          this.btnData = [];
        } else {
          const items = res.data;
          this.btnData = items.map(v => {
            this.$set(v, 'edit', false); // https://vuejs.org/v2/guide/reactivity.html
            v.originalname = v.name;
            v.originalcode = v.code; // will be used when user click the cancel botton
            return v;
          });
        }
      });
    },

    // 点击按钮管理界面 删除按钮
    BtndeleteRow(index, rows, row) {
      const id = rows[index].id;
      // 删除新增的一行
      if (!id) {
        MessageBox.confirm(
          '确定删除吗？', {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          rows.splice(index, 1);
        });
      }
      // 删除菜单按钮
      else {
        MessageBox.confirm(
          '确定删除吗？', {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning'
          }
        ).then(() => {
          buttonDelBtnFunC(id).then((res) => {
            if (res.code == 200) {
              this.$message({
                message: '删除成',
                type: 'succe'
              });
              rows.splice(index, 1);
            } else {
              this.$message({
                message: '删除失败',
                type: 'error'
              });
            }
          });
        });
      }
    },

    // 点击按钮管理界面 取消按钮
    cancelEdit(row) {
      row.name = row.originalname;
      row.code = row.originalcode;
      row.edit = false;
      this.$message({
        message: '取消了编辑',
        type: 'warning'
      });
    },

    // 点击按钮管理界面 增加按钮
    addTableColumn() {
      const list = {
        edit: true,
        name: '',
        code: '',
        menuId: this.checkMenu.id
      };
      this.btnData.push(list);
    },

    // 按钮管理 确定按钮被点击 分两种情况 一种是修改 一种是新增 判断标准为是否有id
    confirmEdit(row) {
      if (row.name == '' || row.code == '') {
        Message({
          message: '请认真填写每一项',
          type: 'error',
          duration: 5 * 1000
        });
        return;
      }
      row.originalname = row.name;
      row.originalcode = row.code;
      row.edit = false;
      // 新增按钮
      if (!row.id) {
        buttonAddBtnFunC(row.code, row.menuId, row.name).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: '增加成功',
              type: 'success'
            });
          } else {
            this.$message({
              message: '增加失败',
              type: 'error'
            });
          }
        });
      }
      // 修改按钮
      else {
        buttonChangeBtnFunC(
          row.id, row.code, row.name
        ).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: '编辑已保存',
              type: 'success'
            });
          } else {
            this.$message({
              message: '编辑保存失败',
              type: 'error'
            });
          }
        });
      }
    },

    /** *************修改 *************/
    // 点击修改按钮 出现弹窗
    toEditor() {
      this.menu = JSON.parse(JSON.stringify(this.checkMenu));
      if (JSON.stringify(this.menu.id) === '') {
        this.$message({
          message: '请先选择要修改的菜单',
          type: 'error'
        });
        return;
      }
      this.dialogEditorVisible = true;
      this.$nextTick(function() {
        // this.$refs.menu.clearValidate() // 移除校验结果
      });
      // 清空父节点
      const obj = {};
      obj.stopPropagation = () => {
      };
      // this.$refs.cascader.clearValue(obj)
    },

    // 点击修改按钮弹窗 确定按钮
    SureToEditor() {
      if (this.menu.icon == '' || this.menu.name == '' || this.menu.orderNum == '' ||
          this.menu.url == '') {
        Message({
          message: '请认真填写每一项',
          type: 'error',
          duration: 5 * 1000
        });
      } else {
        this.menu.pid = this.menu.pidPaths && this.menu.pidPaths.length != 0
          ? this.menu.pidPaths[this.menu.pidPaths.length - 1] : null;
        this.menu.pidPath = this.menu.pidPaths && this.menu.pidPaths.length != 0 ? this.menu.pidPaths.join(',') : null;
        MenuChangeFunC(
          this.menu.id, this.menu.icon, this.menu.name, this.menu.orderNum, this.menu.pidPath, this.menu.pid,
          this.menu.url
        ).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            this.dialogEditorVisible = false;
            this.init();
          } else {
            this.$message({
              message: '修改失败',
              type: 'error'
            });
          }
        });
      }
    },

    /** ************* 删除 *************/
    // 点击删除按钮
    deleteRow(delId) {
      if (delId == '') {
        this.$message({
          message: '请先选择要删除的菜单',
          type: 'error'
        });
        return;
      }
      MessageBox.confirm(
        '确定删除吗？', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        MenuDelFunC(delId).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.init();
          } else {
            this.$message({
              message: '删除失败',
              type: 'warning'
            });
          }
        });
      });
    }
  }
};
</script>

<style scoped lang="scss">
  /*整体布局*/
  .components-container {
    position: relative;
    height: 100vh;
    padding: 20px;
    background-color: rgb(240, 242, 245);
  }

  .menu-container {
    font-size: 18px;
    padding: 20px;
  }

  .menu {
    margin-top: 40px;
    .menu-item {
      padding: 10px;
    }
  }

  .row-right-container {
    width: 100%;
    float: right;
    text-align: right
  }

  .components-container {
    position: relative;
    height: calc(100vh - 50px);
    padding: 20px;
  }

  /*菜单树*/
  .menu-tree-container {
    padding: 20px;
    overflow: auto;
  }

  /*菜单详情标题*/
  .menu-title {
    line-height: 32px;
    padding: 5px 40px;
  }

  .edit-input {
    padding-right: 100px;
  }

  .right-container-bottom {
    margin: 20px;
    padding: 20px;
    .add-table-btn {
      width: 100%;
      height: 40px;
      text-align: center;
      line-height: 40px;
      margin-top: 20px;
      i {
        transform: scale(2);
      }
    }
  }

  /*背景色*/
  .bg {
    background-color: rgb(255, 255, 255);
    margin: 20px;
    border-radius: 10px
  }

  /*靠右*/
  .right {
    float: right;
  }
</style>
